<template>
    <div class="container">
    <a-layout class="course_container">
        <a-layout-header class="course_header">
            <span>课程列表</span>
        </a-layout-header>
        <a-layout-content class="course_content">
            <a-input-search
                    class="course_search"
                    placeholder="输入要查询的课程名"
                    enter-button="Search"
                    allowClear
                    v-model="searchValue"
                    @search="search"
            />
                <a-button type="primary" class="button_contain_item" style="margin-left: 0em" @click="addCourse('')">
                    新建
                </a-button>
                <a-button type="danger" class="button_contain_item" @click="showDeleteCourseModel">
                    删除
                </a-button>
            <a-table ref="tab" class="course_table"
                     size="small"
                     bordered
                     :data-source="dataSource"
                     :columns="columns"
                     :row-selection="{onChange:change}"
                     :pagination="false"
                     :scroll="PageSize === 10||dataSource.length<=10? {}:{ y: 380 }"
                     :rowKey='record=>record.courseId'>
                <template slot="operation" slot-scope="text, record">
                    <a-popconfirm
                            v-if="dataSource.length"
                            title="确认删除吗?"
                            @confirm="() => deleteCourse(record.courseId)"
                    >
                        <a href="#">删除</a>
                    </a-popconfirm>
                    <a href="#" @click="addCourse(record)">编辑</a>
                </template>
            </a-table>
        </a-layout-content>
        <a-layout-footer class="course_footer">
            <a-pagination
                    class="pagination"
                    show-size-changer
                    show-quick-jumper
                    :defaultPageSize="PageSize"
                    :current="currentPage"
                    :total="count"
                    :show-total="total => `共 ${total} 条`"
                    :pageSizeOptions="pageSizeOptions"
                    @change="pageChange"
                    @showSizeChange="showSizeChange"
            />
        </a-layout-footer>
    </a-layout>
<!--        get触发pageChange函数，返回并查询第一页数据-->
<!--        gett触发getCourseList函数，返回当夜数据-->
        <AddCourse ref="addcs" @get="pageChange(1,PageSize)" @gett="pageChange(currentPage,PageSize)"></AddCourse>
<!--        批量删除确认Model-->
<!--        触发批量删除课程-->
        <batch-delete-model ref="deletecs" @del="deleteBatchCourse"></batch-delete-model>
    </div>
</template>

<script>
    import { mapState } from 'vuex'
    import AddCourse from "./AddCourse";
    import BatchDeleteModel from "./BatchDeleteModel";
    export default {
        name: "CourseList",
        data() {
            return {
                flag:0,//标志位，第一次查询时使页面为第一页
                searchValue:'',//查询的课程名
                selectedRowKeys:[],//多选框，存储的值
                count: 0,//总页数
                currentPage:1,//当前页
                PageSize:10,//当前页的大小
                pageSizeOptions:['10','20','30'],//页面可以显示的条数
                //多选（前面复选框的内容）
                dataSource: [],//table中的数据
                columns: [
                    {
                        title: '课程编号',
                        key:'code',
                        dataIndex: 'code',
                        width: '30%',
                        align: 'center'
                    },
                    {
                        title: '课程名',
                        key:'name',
                        dataIndex: 'name',
                        align: 'center',
                        width: '40%',
                    },
                    {
                        title: '操作',
                        key:'operation',
                        align: 'center',
                        scopedSlots: {customRender: 'operation'},
                    },
                ],//每一列的设置
            }
        },
        methods: {
            //获取多选框的值
            change(selectedRowKeys, selectedRows){
                this.selectedRowKeys=selectedRowKeys;
                this.selectedRowKeys=[];
                selectedRows.some(item=>{this.selectedRowKeys.push(item.courseId)});
            },
            //页数变化，并将当前页数和页大小保存起来
            pageChange(page, pageSize){
                this.currentPage = page;
                this.PageSize = pageSize;
                if(this.searchValue === ''){
                    this.getCourseList();
                }else{
                    this.search(this.searchValue)
                }
            },
            //每页显示数量变化，并将当前页和页大小保存起来
            showSizeChange(current, size){
                this.currentPage=1;
                this.PageSize=size;
                if(this.searchValue === ''){
                    this.getCourseList();
                }else{
                    this.search(this.searchValue)
                }
            },
            //删除指定课程，然后调用pageChange函数重新获取dataSource
            //调用pageChange函数，保证删除之后，仍在当前页
            deleteCourse(key) {
                this.$store.dispatch("courseList/deleteCourse",{courseId:key,token:this.accessState.token})
                    .then(()=>{
                        this.$message.success("删除课程成功");
                        this.pageChange(this.currentPage, this.PageSize);
                }).catch(err=>{
                    this.$message.error(err.msg+"：课程存在相关数据");
                })
            },
            //按指定课程名称查找，然后根据查找内容调用不同函数重新获取dataSource
            search(value){
                //查找内容为空时，调用getCourseList函数
                if(value === ''){
                    this.currentPage=1;
                    this.getCourseList();
                    this.flag=0;
                }else{
                    //不为空时，调用queryCourse函数
                    if(this.flag === 0) {this.currentPage=1} //第一次查询时，要到第一页
                    this.flag++;
                    //对参数进行封装
                    const info={
                        courseName: value,
                        collegeId: this.accessState.collegeId,
                        currentPage: this.currentPage,
                        rows: this.PageSize,
                        token: this.accessState.token,
                    };
                    this.$store.dispatch("courseList/queryCourse",info)
                        .then(data=>{
                            this.dataSource=data.data.courseRecordList;
                            this.count=data.data.count;
                        }).catch(err=>{
                        this.$message.error(err.msg);
                    })
                }
            },
            //获取课程列表信息
            getCourseList(){
                //对参数进行封装
                const info={
                    collegeId:this.accessState.collegeId, //获取管理员ID（需要改动）
                    currentPage:this.currentPage,
                    rows:this.PageSize,
                    token:this.accessState.token,
                };
                this.$store.dispatch("courseList/getCourseList",info)
                    .then(data=>{
                        this.dataSource=data.data.courseRecordList;
                        console.log(this.dataSource);
                        this.count=data.data.count;
                    }).catch(err=>{
                    this.$message.error(err.msg);
                })

            },

            //显示批量删除弹窗
            showDeleteCourseModel(){
                if(this.selectedRowKeys.length === 0){
                    this.$message.info('所选内容不能为空');
                }else{
                    this.$refs.deletecs.showModel();
                }
            },
            //批量删除课程
            deleteBatchCourse(){
                this.$store.dispatch("courseList/deleteBatchCourse",{courseIds:this.selectedRowKeys,token:this.accessState.token})
                    .then(()=>{
                        this.$message.success("删除课程成功");
                        this.pageChange(this.currentPage, this.PageSize);
                        this.selectedRowKeys=[];
                    }).catch(err=>{
                    this.$message.error(err.msg);
                })
            },
            //新建课程，调用Modal方法，使Modal显示出来
            addCourse(judge){
                this.$refs.addcs.showModel(judge);
            }
        },
        //初始化时，获取所有课程列表
        created() {
                this.getCourseList();
        },
        components:{
            AddCourse,
            BatchDeleteModel
        },
        computed: {
            ...mapState({ // 这个是提取store中access文件夹目录下的数据
                'accessState': 'access',
                'courseListState':'courseList',
            })
        }
    }
</script>

<style scoped>
    .container{
        width: 100%;
        height: 100%;
    }
    .course_container{
        width: 100%;
        background-color: #fff;
    }
    .course_header{
        height: 2.8em;
        text-align: left;
        font-size: 1.4em;
        font-weight: bolder;
        background-color: #fff;
        padding: 0em 1.5em;
    }
    .course_content{
        text-align: left;
        padding: 0em 2em;
        overflow: hidden;
    }
    .course_search{
        width: 30em;
        display: block;
    }
    .button_contain_item{
        width: 6em;
        margin: 1em 1.5em;
    }
    a{
        margin: 1em ;
    }
    .course_footer{
        background-color: #fff;
    }
</style>
<style>
    .course_table th{
        background-color: #cccccc !important;
        font-size: 1em !important;
        font-weight: bold !important;
    }
</style>
